package com.dahuyou.netty.customercodec.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道建立成功");
        // 通知客户端链接建立成功
/*
        String str = "hello server , i'm client very happy connect to you." + " " + new Date() + " " + ((SocketChannel) ctx.channel()).localAddress().getHostString() + "\r\n";
*/
        String xxx = "a1b2";
        System.out.println(xxx.getBytes());
        byte[] bytes = xxx.getBytes();

        // 增加stx length etx
        byte[] send = new byte[bytes.length + 3];
        System.arraycopy(bytes, 0, send, 2, bytes.length);
        send[0] = 0x02; // stx
        send[1] = 0X34; // length 4的ASCII码是52 十六进制就是34
        send[send.length - 1] = 0x03; // etx

        ByteBuf buf = Unpooled.buffer(send.length/* + 3*/); // + 3 stx 长度 etx
        buf.writeBytes(send);

//       ctx.writeAndFlush(str);
       ctx.writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收msg消息{与上一章节相比，此处已经不需要自己进行解码}
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " receive msg: " + msg);
        //通知客户端链消息发送成功
//        String str = "hello server received your msg: " + new Date() + " " + msg + "\r\n";
//        ctx.writeAndFlush(str);

    }
}
